package com.whu.bookstore.util;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;


/**
 * Created by 11956 on 2017/4/14.
 * hibernate工具类
 */
public class HibernateUtil {

    // 创建线程局部变量threadLocal，用来保存Hibernate的Session
    private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private static SessionFactory sessionFactory;

    static {
        final StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .configure("hibernate.cfg.xml").build();
        try {
            System.out.println("====static===" + serviceRegistry);
            MetadataSources sources = new MetadataSources(serviceRegistry);
            System.out.println("====sources===" + sources);
            Metadata metadata = sources.buildMetadata();
            System.out.println("====metadata===" + metadata);
            sessionFactory = metadata.buildSessionFactory();
            System.out.println("====sessionFactory===" + sessionFactory);
        } catch (Exception e) {
            e.printStackTrace();
            StandardServiceRegistryBuilder.destroy(serviceRegistry);
        }

    }

    private HibernateUtil () {
    }

    // 获得SessionFactory的实例
    public static SessionFactory getsSessionFactory() {
        return sessionFactory;
    }

    // 获得ThreadLocal对象管理的Session
    public static Session getsSession() throws HibernateException {


        Session session = threadLocal.get();
        if (session == null || !session.isOpen()) {
            if (sessionFactory == null) {
                rebuildSessionFactory();
            }
            // 通过SessionFactory对象创建Session对象
            session = (sessionFactory != null) ? sessionFactory.openSession() : null;
            // 将Session对象保存到线程局部变量threadLocal中
            threadLocal.set(session);
        }
        return session;
    }

    // 关闭Session实例
    public static void closeSession() {
        // 从线程局部变量threadLocal中获取之前存入的Session实例
        Session session = threadLocal.get();
        threadLocal.set(null);
        if (session != null) {
            session.close();
        }
    }

    // 重建SessionFactory
    public static void rebuildSessionFactory() {
        final StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .configure("hibernate.cfg.xml").build();
        try {
            System.out.println("===" + serviceRegistry);
            sessionFactory = new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();

        } catch (Exception e) {
            e.printStackTrace();
            StandardServiceRegistryBuilder.destroy(serviceRegistry);
        }
    }

    // 关闭缓存和连接池
    public static void shutdown() {
        getsSessionFactory().close();
    }

    public static void closeSession(Session session) {
        if (session != null) {
            session.close();
        }
    }
}
